<template>

	<view style="width: 100%;height: 100%; display: block;">
		<!-- 上方商品特写 -->
		<tn-swiper v-model="curSwiperIndex" :data="tmpData?.banner" width="100%" :height="proH+'px'" autoplay indicator>
			<template #default="{ data }">
				<view style="width: 100%;height: 100%;">
					<image :src="sConf.pics + data" mode="aspectFit"
						style="width: 100%;height: 100%;border-radius: inherit;background-color: black;">
					</image>
				</view>
			</template>
		</tn-swiper>

		<!-- 头部 -->
		<tn-sticky enabled :offset-top="sConf.tH">
			<view
				style="padding: 5px; background-color: #fff2f2;border-radius: 10px;display: flex;flex-direction: column;gap: 5px;margin: 10px;">
				<!-- 产品名称 -->
				<view style="font-weight: bolder;font-size: larger; padding: 5px;"> {{ tmpData?.jingle.title }} </view>
				<!-- 广告词 -->
				<view style="padding:5px; color: #888;">{{ tmpData?.jingle.jingle }}</view>
			</view>
		</tn-sticky>
		<!-- 组件 -->
		<sub-prodict-info-card v-if="tmpData !== null" :data="tmpData" :card="curMode === 0" :point="curMode === 1"
			:master="curMode === 2" :money="curMode === 9" @curSpecs="specsChange"></sub-prodict-info-card>
		<!-- 正文 -->

		<!-- 分段器 -->
		<view style="padding: 5; background-color: #fff;border-radius: 10px;margin-top: 10px;">
			<tn-subsection v-model="selfSubsection" mode="button">
				<tn-subsection-item title="详情"></tn-subsection-item>
				<tn-subsection-item title="参数"></tn-subsection-item>
				<tn-subsection-item title="评论"></tn-subsection-item>
			</tn-subsection>
			<view v-if="selfSubsection === 0" style="padding: 10px;">
				<tn-read-more :height="150" expand-text="查看更多"><rich-text
						:nodes="tmpData?.jingle.content"></rich-text></tn-read-more>
			</view>
			<view v-if="selfSubsection === 1" style="padding: 10px;">
				<tn-list-item v-if="tmpData?.args.length === 0">
					<tn-empty mode="data"></tn-empty>
				</tn-list-item>
				<tn-list-item v-for="(args, index) in tmpData?.args" :key="index" height="28px">
					{{ args.name }}: {{ args.value }}
				</tn-list-item>
			</view>
			<view v-if="selfSubsection === 2" style="padding: 10px;">
				<tn-list-item v-if="tmpData?.comment.length === 0">
					<tn-empty mode="comment"></tn-empty>
				</tn-list-item>
				<tn-list-item v-for="(args, index) in tmpData?.comment" :key="index">
					<view style="display: flex;flex-direction: column;">
						<view style="display: flex;justify-content: space-between;">
							<view class="">
								{{ args.name }}
							</view>
							<view class="">
								<tn-rate v-model="args.rate" allow-half readonly :min="0" :max="5"></tn-rate>
							</view>
						</view>
						<view style="padding: 10px;">
							{{ args.value }}
						</view>
					</view>
				</tn-list-item>
			</view>
		</view>
		<image v-for="url in tmpData?.info" :key="url" :src="sConf.pics + url" mode="widthFix" />



		<!-- 顶部自定义导航 -->
		<tn-navbar :placeholder="true" fixed bg-color="#FFFFFF00" text-color="#fff">{{ tmpData?.name }}</tn-navbar>

		<!-- 商品导航 -->
		<view class="goods-carts" style="padding: 10px 0 15px 0;background-color: #fff;">
			<uni-goods-nav :fill="true" :options="navOptions" :button-group="navGroup" @click="navOnClick"
				@buttonClick="navButtonClick"></uni-goods-nav>
		</view>
	</view>


	<!-- 直接下单 -->
	<tn-popup v-model="showPay" open-direction="bottom">
		<view v-if="tmpData !== null" class="tn-p-lg" style="background-color: #f1f1f1;padding: 10px;">
			<!-- 产品缩影 -->
			<view style="display: flex;gap: 10px;">
				<image :src="sConf.pics + (tmpData?.cover ?? [])[0]?.url" mode="aspectFill"
					style="width: 64px;height: 64px;border-radius: 10px;"></image>
				<view style="display: flex;flex-direction: column;justify-content: space-between;">
					<view style="font-weight: bolder;"> {{ tmpData?.jingle.title }} </view>
					<view style="color: #aaa;font-size: smaller;">{{ tmpData?.jingle.jingle }}</view>
					<view style="display: flex;gap: 10px;">
						<view style="color: #666;font-size: smaller;display: flex;align-items: flex-end;">
							<text>指导价￥</text>
							<view class="buy-price">
								{{ (curOalMoney / 100).toFixed(2) }}
							</view>
						</view>
						<view style="color: #dd524d;font-size: smaller;display: flex;align-items: flex-end;">
							<text>会员价￥</text>
							<view class="buy-price">
								{{ (curVipMoney / 100).toFixed(2) }}
							</view>
						</view>
						<view v-if="tmpData?.is_points"
							style="color: #007aff;font-size: smaller;display: flex;align-items: flex-end;">
							<tn-icon name="funds" color="#007aff"></tn-icon>
							<view class="buy-price">{{ curSpecs ? curSpecs.point : tmpData.cur_point }} </view>
						</view>
					</view>
				</view>
			</view>

			<view style="margin: 10px 0;padding: 10px; border-radius: 10px;background-color: #fff;">
				<!-- 规格 -->
				<view v-if="curSpecs"
					style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">
					<view style="font-weight: bold;"> 规格 </view>
					<view
						style="display: flex; align-items: center;gap: 5px;padding: 5px;border-radius: 5px; background-color: #ddd;">
						<tn-avatar :url="sConf.pics + curSpecs.icon" size="sm" shape="square"></tn-avatar>
						<view class="">{{ curSpecs.name }}</view>
						<view v-if="isVip" style="color: #ff6b6b;font-weight: bold;">
							￥{{ (curSpecs.price / 100).toFixed(2) }}</view>
						<view v-else style="color: #999;font-weight: bold;">￥{{ (curSpecs.money / 100).toFixed(2) }}
						</view>
						<view v-if="tmpData?.is_points" style="color: #007aff;font-weight: bold;"><text
								style="font-size: small;">积分兑换 </text>{{ curSpecs.point }}</view>
					</view>
				</view>
				<!-- 数量 -->
				<view style="padding: 10px;display: flex;justify-content: space-between;">
					<view style="font-weight: bold;"> 数量 </view>
					<view class="">
						<text style="color: #aaa;">限购{{ maxCount }}件 </text>
						<tn-number-box v-model="curPayCount" :min="1" :max="maxCount" input-disabled
							@change="localCalcPrice"></tn-number-box>
					</view>
				</view>

				<!-- 收货地址 -->
				<view v-if="tmpData.is_virtual !== 1" style="padding: 10px;display: flex;justify-content:space-between;"
					:class="warn ? 'warn-address' : ''" @tap="addressChange">
					<view style="font-weight: bold;"> 地址 </view>
					<view v-if="curAddress">
						<view> {{ zipStr(curAddress?.name) }} {{ zipStr(curAddress?.phone) }}</view>
						<view>{{ curAddress?.sheng }} {{ curAddress?.shi }} {{ curAddress?.xian }} </view>
						<view> {{ curAddress?.address }}</view>
					</view>
					<view v-else>
						<text style="color: #aaa;">请选择收货地址</text>
					</view>
				</view>
			</view>

			<view style="margin: 10px 0;padding: 10px;border-radius: 10px;background-color: #fff;">
				<!-- 支付方式 -->
				<view style="padding: 10px;display: flex;justify-content:space-between;align-items: center; "
					@tap="paymentChange">
					<view style="font-weight: bold;"> 支付方式 </view>
					<view style="display: flex;align-items: center;gap: 5px;">
						<tn-icon :name="curPayMent?.icon" :color="curPayMent?.color" size="64"></tn-icon>
						<text>{{ curPayMent?.text }}</text>
					</view>
				</view>
			</view>

			<view style="margin: 10px 0;padding: 10px;border-radius: 10px;background-color: #fff;">
				<!-- 折扣 -->
				<view
					v-if="['wxpay', 'wallet'].includes(curPayMent?.value) && curCardGood === null && tmpData?.is_master === 1 && curSpecs?.discount !== 1"
					style="padding: 10px;border-radius: 10px; display: flex;justify-content: space-between;">
					<view style="font-weight: bold;"> 会员折扣 </view>
					<view style="color: #aaa;">{{ curRate < 100 ? (curRate / 10) + '折' : '无折扣' }}</view>
				</view>
				<!-- 卡券 停用
				<view v-if="['wxpay', 'wallet'].includes(curPayMent?.value) && tmpData?.is_card === 1"
					@tap="cardGoodChange"
					style="padding: 10px;border-radius: 10px;display: flex;justify-content: space-between;">
					<view style="font-weight: bold;"> 兑换券 </view>
					<view style="color: #aaa;">{{ curCardGood ? curCardGood.cardpt.name : '无卡券' }}</view>
				</view>
				-->
				<!-- 代金券 -->
				<view
					v-if="['wxpay', 'wallet'].includes(curPayMent?.value) && tmpData?.is_master !== 1 && cardMoneyData.length > 0"
					@tap="cardMoneyChange"
					style="padding: 10px;border-radius: 10px;display: flex;justify-content: space-between;">
					<view style="font-weight: bold;"> 代金券 </view>
					<view style="color: #aaa;">
						{{ curCardMoney ? (curCardMoney.value / 100).toFixed(2) + '元' : '选择代金券' }}
					</view>
				</view>
				<!-- 备注 -->
				<view style="padding: 10px;border-radius: 10px;display: flex;justify-content: space-between;">
					<view style="font-weight: bold;"> 备注 </view>
					<view style="color: #aaa;" @click="showNodeBlock">{{ nodeData ?? '无备注' }} ></view>
				</view>
			</view>

			<!-- 支付按钮 reqsnChange subDisable || -->
			<view :class="curAddress === null ? 'disableButton' : 'toSubmitReqsn'"
				style="margin: 10px 0; border-radius: 10px;padding: 10px;display: flex;justify-content: center;color: #fff;"
				@click="readPutOrder">
				<view> 提交订单 </view>
			</view>

			<!-- 选择收货地址 -->
			<tn-action-sheet ref="actionSheetAddress">
				<template #title>
					<view style="display: flex;justify-content: space-between;width: 100%;">
						<view>选择收货地址</view>
						<view @click="navToAddress">其他地址</view>
					</view>
				</template>
			</tn-action-sheet>

			<!-- 选择其他 -->
			<tn-action-sheet ref="actionSheetRef"></tn-action-sheet>

			<!-- 填写备注 -->
			<tn-popup v-model="showNode" open-direction="bottom">
				<view class="tn-p-lg" style="background-color: #fff;padding: 10px;">
					<view style="font-weight: bold;"> 备注 </view>
					<textarea :value="nodeData ?? ''" placeholder-style="color:#aaa" maxlength="255"
						@input="conformNode" placeholder="选填,建议先与商家协商一致"
						style="background-color: #f1f1f1;width: 100%;height: 20vh;padding: 10px;border-radius: 10px;margin-top: 10px;"></textarea>
					<view class="toSubmitReqsn"
						style="border-radius: 10px;margin-top:10px;padding: 10px;display: flex;justify-content: center;color: #fff;"
						@click="showNodeBlock">
						<view class=""> 提交 </view>
					</view>
				</view>
			</tn-popup>
		</view>
	</tn-popup>
</template>

<script>
	import utils from '@/common/utils';
	import psMethod from '@/common/psMethod';
	export default {
		data() {
			return {
				proH: '350', // 比例高度
				title: '产品详情',
				sConf: getApp().globalData,
				gid: null, // 传入的产品ID
				parent: null, // 传入的推荐者
				tmpData: null,
				curSwiperIndex: 0,
				curMode: 9,
				isVip: false,



				curQuoat: null, // 当前用户限购规则
				curQuoatFund: 0, // 当前用户限购数量
				curStaffQuoat: 0, // 当前用户限购-已购数量				

				curSpecs: null, // 选择规格
				curAddress: null, // 收货地址
				curTtlMoney: 0, // 结算分佣价格
				curPerMoney: 0, // 业绩分佣价格
				curOalMoney: 0, // 当前原价
				curVipMoney: 0, // 会员价
				curPayMoney: 0, // 当前支付金额
				curRedMoney: 0, // 当前红包兑换价格
				curIntMoney: 0, // 当前积分兑换价格
				curPayCount: 1, // 当前数量
				curPayMent: null, // 支付方式
				curCardGood: null, // 当前兑换券 废弃
				curCardMoney: null, // 当前代金券
				curRate: 100, // 当前折扣

				curStaff: null, // 当前用户
				curPayProduct: null, // 当前购物车对象
				cardMoneyData: [], // 代金券
				cardGoodsData: [], // 兑换券
				addressData: [], // 用户地址
				selfSubsection: 0, // 分段器	
				subDisable: true, // 禁止提交			
				showPay: false, // 显示支付类型列表
				showNode: false, // 显示订单备注编辑
				warn: false, // 警告消息	
				maxCount: 0, // 最大数量
				nodeData: null, // 备注
				paymentData: [{
					text: '微信支付',
					value: 'wxpay',
					icon: 'payment-wechat',
					color: '#48AC35'
				}, {
					text: '钱包支付',
					value: 'wallet',
					icon: 'pay-fill',
					color: '#00b09b'
				}, {
					text: '红包抵扣',
					value: 'master',
					icon: 'lucky-money-fill',
					color: '#dd524d',
					desc: '仅部分商品支持红包抵扣'
				}, {
					text: '积分兑换',
					value: 'point',
					icon: 'funds-fill',
					color: '#007aff',
					desc: '仅部分商品支持红包抵扣'
				}, {
					text: '支付宝',
					value: 'zhifubao',
					icon: 'payment-alipay',
					color: '#4FA2E7',
					desc: '暂不支持'
				}],
				navOptions: [{
					icon: 'shop',
					text: '店铺'
				}, {
					icon: 'chat',
					text: '客服'
				}, {
					icon: 'heart',
					text: '收藏'
				}, {
					icon: 'cart',
					text: '购物车'
				}],
				navGroup: [{
						text: '加入购物车',
						backgroundColor: 'linear-gradient(90deg, #60F3FF, #088FEB,#60F3FF)',
						color: '#fff',
						disable: true
					},
					{
						text: '立即购买',
						backgroundColor: 'linear-gradient(90deg, #60F3FF, #088FEB,#60F3FF)',
						color: '#fff'
					}
				],

			}
		},
		onLoad(args) {
			const gid = Number(args.gid || 0);
			const mode = Number(args.mode || 9);
			const parent = Number(args.parent || null);
			console.log('onLoad prodict', gid, parent);
			// this.proH = Math.ceil(this.sConf.iW / 3 * 4)
			this.proH = this.sConf.iW
			this.gid = gid
			this.parent = parent
			// mode:0 兑换券模式 
			// mode:1 积分模式
			// mode:2 抵扣额度
			// mode:9 在线支付
			this.curMode = mode;
			this.curPayMent = this.convolPayment('wxpay');

			// if (!this.sConf.auth) {
			// 	console.log('未登录');
			// 	this.autoLogin()
			// } else {
			// 	console.log('已登录');
			// 	this.bindParentStaff(this.parent).then(res => {
			// 		console.log('已登录__检查绑定->', res);
			// 	}).catch(err => {
			// 		console.log('已登录__检查绑定=>', err);
			// 	})				
			// }
		},
		onReady() {
			console.log('onReady product');
			// if(!this.sConf.auth){
			// 	uni.reLaunch({
			// 		url:'/pages/login/login?staff='+this.parent +'&url='+'product'
			// 	})
			// }
			this.loadDefData(this.gid)
		},
		onShow() {
			console.log('onShow');

		},
		onShareAppMessage(e) {
			console.log('onShareAppMessage', e);
			let url = this.sConf.pics;
			let path = '/pageb/staff/share?gid=' + this.tmpData?.id + '&parent=' + this.sConf.auth.id;
			console.log('path', path);
			return {
				title: this.tmpData.jingle.title,
				path: path,
				imageUrl: url + (this.tmpData?.banner ?? [])[0]
			}
		},
		onShareTimeline(e) {
			console.log('onShareTimeline', e);
			let url = this.sConf.pics;
			let path = '/pageb/staff/share';
			let args = 'gid=' + this.tmpData?.id + '&parent=' + this.sConf.auth.id;
			console.log('path', path, args);
			return {
				title: this.tmpData.jingle.title,
				path: path,
				imageUrl: url + (this.tmpData?.banner ?? [])[0],
				query: args
			}
		},
		methods: {
			async autoLogin() {
				console.log('无用户登录-自动登录');
				let code = await uni.login({
					provider: 'weixin',
					onlyAuthorize: true
				})
				console.log('wxCode->', code.code);
				let login = await this.hasWxCode(code.code).then(res => {
					console.log('登录完成->', res);
					this.sConf.auth = res.auth
					this.sConf.token = res.token
				})
				let bind = await this.bindParentStaff(this.parent).then(res => {
					console.log('检查绑定->', res);
				}).catch(err => {
					console.log('检查绑定=>', err);
				})

				this.loadDefData(this.gid)
			},
			bindParentStaff(e) {
				console.log('bindParentStaff', e);
				return new Promise((resolve, reject) => {
					if (!Boolean(this.sConf.auth.parent) && Boolean(e) && this.sConf.auth.id !== e) {
						let host = this.sConf.host + '/weapps/bindHelp/';
						let token = this.sConf.token || ''
						let data = {
							parent: e
						}
						utils.authenticatorOnPost(host, token, data).then(res => {
							console.log('绑定推荐', res);
							resolve(res.resmsg)
						}).catch(err => {
							reject(err)
						})
					} else {
						reject('不需要绑定')
					}
				})
			},

			hasWxCode(e) {
				let host = this.sConf.host + '/weapps/login/'
				let data = {
					code: e
				}
				return new Promise((resolve, reject) => {
					psMethod.requestPostSync(host, data).then(res => {
						console.log('微信快速登录->', res);
						resolve(res.resmsg)
					}).catch(err => {
						reject(err)
					})
				})
			},
			/**
			 * 加载默认数据
			 */
			async loadDefData(e) {

				let host = this.sConf.host + '/weapps/product/' + e + '/';
				let token = this.sConf.token || '';
				await utils.httpRequestOnRead(host).then(res => {
					console.log('加载默认数据', res);
					this.tmpData = res
					this.maxCount = res.cur_num
					if (res.cur_num > 0) {
						this.curPayCount = 1
					}
					console.log('选择SKU', res.specs.length);
					if (res.specs && res.specs.length > 0) {
						this.specsChange(res.specs[0])
					}
				}).catch(err => {
					console.log('加载默认数据__失败', err);
				})
			},
			/**
			 * 导航栏小按钮
			 */
			navOnClick(e) {
				console.log('navOnClick', e);
				if (e.index === 0) {
					uni.navigateTo({
						url: '/pageb/shoped/shoped?pid=' + this.tmpData.pid
					})
				} else if (e.index === 1) {
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
					uni.showToast({
						icon: 'error',
						title: '尚未开放'
					});
				} else if (e.index === 2) {
					this.favorChange()
				} else if (e.index == 3) {
					uni.navigateTo({
						url: '/pageb/puctcart/puctcart'
					});
				} else {}
			},
			/**
			 * 导航栏大按钮
			 */
			async navButtonClick(e) {
				console.log('navButtonClick', e);
				if (this.tmpData.specs.length > 0 && this.curSpecs === null) {
					uni.showToast({
						icon: 'error',
						title: '选择商品规格'
					})
					return
				}
				if (e.index === 0) {
					this.byCart();
				}
				if (e.index === 1) {
					console.log('准备提交订单...');

					if (!this.curSpecs) {
						uni.showModal({
							title: '错误',
							content: '请选择心仪的产品规格',
							showCancel: false
						})
						return
					}

					await this.loadStaffInfo(this.sConf.auth.id).then(res => {
						console.log('加载用户信息', res);
						this.curStaff = res;
						this.isVip = res.curLevel.level > 1 ? true : false
						if (this.tmpData.is_master === 1) {
							// 仅体系产品参与会员折扣
							this.curRate = res.curLevel.discount;
						}
						if (this.curSpecs.sub_quoat.length > 0) {
							this.curQuoat = this.curSpecs.sub_quoat.find(item => item.level === res.curLevel
								.level)
							console.log('限购规则->', this.curQuoat);
						}
					})

					// 检查等级要求
					if (this.curSpecs.need_level && this.curStaff.curLevel.level < this.curSpecs.need_level) {
						uni.showModal({
							title: '失败',
							content: '该商品需要更高的权益等级',
							showCancel: false
						})
						return
					}

					// 计算限购
					if (this.curQuoat) {
						await this.loadQuoatForStaff().then(res => {
							let tmpData = 0
							res.forEach(item => {
								if (item.status === 1) {
									tmpData += item.fund
								}
							})
							this.curStaffQuoat = tmpData
							let curCount = this.curQuoat.fund - tmpData
							if (this.maxCount > curCount) {
								this.maxCount = curCount
							}
						})
					}
					console.log('当前用户限购历史->', this.curStaffQuoat);


					// 检测库存
					if (this.maxCount < 1) {
						uni.showModal({
							title: '失败',
							content: '该商品库存不足',
							showCancel: false
						})
						return
					}

					await this.loadStaffAddress().then(res => {
						this.addressData = res
					});

					// 禁用兑换券
					// if (this.tmpData.is_card === 1) {
					// 	await this.loadStaffCardGood(this.sConf.auth.id).then(res => {
					// 		this.cardGoodsData = res;
					// 	})
					// }

					if (this.tmpData.is_master !== 1) {
						await this.loadStaffCardMoney(this.sConf.auth.id).then(res => {
							this.cardMoneyData = res;
						})
					}
					// 本地计算价格
					await this.localCalcPrice().then(res => {
						this.showPay = !this.showPay;
					}).catch(err => {
						uni.showModal({
							title: '失败',
							content: err,
							showCancel: false
						})
					})
				} else {
					console.log('error');
				}

			},
			/**
			 * 加入购物车
			 */
			byCart() {
				console.log('byCart');
				let host = this.sConf.host + '/weapps/cart/';
				let token = this.sConf.token || '';
				let data = {
					sid: this.sConf.auth.id,
					puid: this.tmpData.id,
					pid: this.tmpData.pid,
					num: 1,
					status: 1
				}
				if (this.curSpecs !== null) {
					data.pusid = this.curSpecs.id
				}
				utils.authenticatorOnPost(host, token, data).then(res => {
					console.log('请求成功', res);
					uni.showToast({
						icon: 'success',
						title: '加入购物袋'
					})
				}).catch(err => {
					uni.showToast({
						icon: 'error',
						title: '失败'
					})
				});
			},
			/**
			 * 添加到收藏夹
			 */
			favorChange() {
				console.log('favorChange');
				let host = this.sConf.host + '/weapps/favored/'
				let token = this.sConf.token
				let data = {
					sid: this.sConf.auth.id,
					puid: this.tmpData.id,
					status: 1
				}
				utils.authenticatorOnPost(host, token, data).then(res => {
					uni.showToast({
						icon: 'success',
						title: '加入收藏夹'
					})
				}).catch(err => {
					uni.showToast({
						icon: 'error',
						title: '失败'
					})
				});
			},
			navToAddress() {
				uni.navigateTo({
					url: '/pageb/userinfo/address'
				})
			},
			zipStr(e) {
				return utils.zipStr(e)
			},
			/**
			 * 转换支付对象
			 */
			convolPayment(e) {
				return this.paymentData.find(item => item.value === e)
			},
			/**
			 * 转换地址对象
			 */
			convolAddress(e) {
				return this.addressData.find(item => item.id === e)
			},
			/**
			 * 转换兑换券对象
			 */
			convolCardGood(e) {
				return this.cardGoodsData.find(item => item.id === e)
			},
			/**
			 * 转换代金券对象
			 */
			convolCardMoney(e) {
				return this.cardMoneyData.find(item => item.id === e)
			},
			/**
			 * 加载用户兑换券
			 */
			loadStaffCardGood(e) {
				let host = this.sConf.host + '/weapps/goodCard/';
				let token = this.sConf.token || '';
				let data = {
					sid: this.sConf.auth.id,
					status: 1
				}
				return new Promise((resolve, reject) => {
					utils.authenticatorOnList(host, token, data).then((res) => {
						console.log('加载用户兑换券', res);
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})

			},
			/**
			 * 加载用户代金券
			 */
			loadStaffCardMoney(e) {
				let host = this.sConf.host + '/weapps/myCard/';
				let token = this.sConf.token || '';
				let data = {
					sid: this.sConf.auth.id,
					status: 1
				}
				return new Promise((resolve, reject) => {
					utils.authenticatorOnList(host, token, data).then((res) => {
						console.log('加载用户代金券', res);
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})

			},
			/**
			 * 加载用户信息
			 */
			loadStaffInfo(e) {
				let host = this.sConf.host + '/weapps/userinfo/' + e + '/';
				let token = this.sConf.token || '';
				return new Promise((resolve, reject) => {
					utils.authenticatorOnRead(host, token).then(res => {
						console.log('加载用户信息', res);
						resolve(res)
					}).catch(err => {
						console.log('加载用户信息__失败', err);
						reject(err)
					})
				})
			},
			/**
			 * 加载限购数量
			 */
			loadQuoatForStaff() {
				let host = this.sConf.host + '/weapps/hasQuoat/'
				let token = this.sConf.token || '';
				let data = {
					sid: this.curStaff.id,
					sku: this.curSpecs.id
				}
				return new Promise((resolve, reject) => {
					utils.authenticatorOnList(host, token, data).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			/**
			 * 加载用户收货地址
			 */
			loadStaffAddress() {
				let host = this.sConf.host + '/weapps/address/';
				let token = this.sConf.token || '';
				let data = {
					sid: this.sConf.auth.id
				}
				return new Promise((resolve, reject) => {
					utils.authenticatorOnList(host, token, data).then((res) => {
						console.log('加载收货地址', res);
						resolve(res)
					}).catch(err => {
						reject(err)
					});
				})

			},
			/**
			 * 调出收货地址选项框
			 */
			addressChange() {
				console.log('addressChange');
				let tmpData = []
				this.addressData.forEach(item => {
					if (item.zhen) {
						tmpData.push({
							value: item.id,
							text: this.zipStr(item.name) + ' ' + this.zipStr(item.phone),
							desc: item.address
						})
					}
					console.log('转换数据.');
				})
				let that = this
				this.$refs.actionSheetAddress.show({
					actions: tmpData,
					title: '请选择收货信息',
					cancel: () => {
						return true
					},
					select: (index, value) => {
						console.log('选项被点击', index, value)
						that.curAddress = that.convolAddress(value)
						that.warn = false
						return true
					}
				})
			},
			/**
			 * 调出选择支付方式
			 */
			paymentChange() {
				let that = this
				let tmpData = []
				console.log(this.curStaff);
				this.paymentData.forEach(item => {
					if (item.value === 'wxpay' && that.tmpData.is_money === 1) {
						tmpData.push(item)
					}
					if (item.value === 'wallet' && that.tmpData.is_money === 1) {
						let inter = that.curStaff.wallet.amount
						item.desc = '当前余额:' + (inter / 100).toFixed(2)
						tmpData.push(item)
					}
					if (item.value === 'point' && that.tmpData.is_points === 1) {
						let inter = that.curStaff.points.amount
						item.desc = '当前余额:' + inter
						tmpData.push(item)
					}
					if (item.value === 'master' && that.tmpData.is_master === 1) {
						let inter = that.curStaff.master.amount
						item.desc = '当前余额:' + (inter / 100).toFixed(2)
						tmpData.push(item)
					}
				});
				this.$refs.actionSheetRef.show({
					actions: tmpData,
					title: '选择支付方式',
					cancel() {
						console.log('取消选择');
						return true
					},
					select(index, value) {
						console.log('选项被点击', index, value)
						if (value === 'zhifubao') {
							return false
						}
						if (value === 'wallet' && (that.tmpData.is_money !== 1 || that.curStaff.wallet.amount <
								that.curPayMoney)) {
							uni.showToast({
								icon: 'error',
								title: '支付方式不支持'
							})
							return false
						}
						if (value === 'point' && (that.tmpData.is_points !== 1 || that.curStaff.points.amount <
								that.curIntMoney)) {
							uni.showToast({
								icon: 'error',
								title: '支付方式不支持'
							})
							return false
						}
						if (value === 'master' && (that.tmpData.is_master !== 1 || that.curStaff.master.amount <
								that.curRedMoney)) {
							uni.showToast({
								icon: 'error',
								title: '支付方式不支持'
							})
							return false
						}

						let tmpMent = that.convolPayment(value);
						if (tmpMent !== that.curPayMent) {
							that.curPayMent = tmpMent
							that.curCardGood = null;
							that.curCardMoney = null;
						}

						return true
					}
				})
			},
			/**
			 * 调出选择兑换券
			 */
			cardGoodChange() {
				let that = this
				let tmpData = []
				this.cardGoodsData.forEach(item => {
					if (item.rate === that.tmpData.id) {
						tmpData.push({
							value: item.id,
							text: that.tmpData.name,
							desc: '兑换券'
						})
					}
					console.log('转换数据.');
				});
				this.$refs.actionSheetRef.show({
					actions: tmpData,
					title: '请选择兑换券',
					cancel: () => {
						return true
					},
					select: (index, value) => {
						console.log('选项被点击', index, value)
						that.curCardGood = that.convolCardGood(value)
						return true
					}
				})
			},
			/**
			 * 调出选择代金券
			 */
			cardMoneyChange() {
				let that = this
				let tmpData = []
				let aprice = []
				this.cardMoneyData.forEach(item => {
					if (!aprice.includes(item.value)) {
						// 唯一面额
						if (that.tmpData.is_master !== 1 && (item.pid === 0 || item.pid === that.tmpData.pid) &&
							that.curOalMoney > item.factor) {
							let text = item.factor > 0 ? '代金券 满 ' + (item.factor / 100).toFixed(2) + ' 可用' : '通用'
							tmpData.push({
								value: item.id,
								text: (item.value / 100).toFixed(2) + '元',
								desc: text
							})
						}
						aprice.push(item.value);
					}
					console.log('转换数据.');
				});
				this.$refs.actionSheetRef.show({
					actions: tmpData,
					title: '请选择代金券',
					cancel: () => {
						return true
					},
					select: (index, value) => {
						console.log('请选择代金券', index, value)
						that.curCardMoney = that.convolCardMoney(value)
						// 本地计算
						that.localCalcPrice()
						return true
					}
				})
			},
			/**
			 * 选择规格
			 */
			specsChange(e) {
				console.log('specsChange', e);
				this.curSpecs = e;
				this.maxCount = e.fund;
			},
			/**
			 * 备注部分
			 */
			showNodeBlock() {
				this.showNode = !this.showNode
			},
			conformNode(e) {
				this.nodeData = e.detail.value
			},
			/**
			 * 本地计算价格
			 */
			localCalcPrice() {
				console.log('localCalcPrice');
				console.log('curStaff->', this.curStaff);
				console.log('curSpu->', this.tmpData);
				console.log('curSku->', this.curSpecs);
				console.log('curCardMoney->', this.curCardMoney);
				console.log('curRate', this.curRate);
				console.log('curPayCount->', this.curPayCount);
				let isVip = this.curStaff.curLevel.level > 1 ? true : false
				let curTtlMoney = 0
				let curPerMoney = 0 // 当前业绩分佣
				let curOalMoney = 0
				let curVipMoney = 0
				let curPayMoney = 0
				let curRedMoney = 0
				let curIntMoney = 0
				let that = this
				return new Promise((resolve, reject) => {
					if (Boolean(that.curSpecs)) {
						curPerMoney = that.curSpecs.setprice * that.curPayCount
						curOalMoney = that.curSpecs.money //* that.curPayCount
						curVipMoney = that.curSpecs.price //* that.curPayCount
						// 判断会员价
						curPayMoney = that.curStaff.curLevel.level > 1 ? that.curSpecs.price * that.curPayCount :
							that.curSpecs.money * that.curPayCount
					} else {
						curTtlMoney = that.tmpData.cur_price * that.curPayCount
						curPerMoney = that.tmpData.cur_price * that.curPayCount
						curOalMoney = that.tmpData.price.money //* that.curPayCount
						curVipMoney = that.tmpData.price.price //* that.curPayCount
						// 判断会员价
						curPayMoney = that.curStaff.curLevel.level > 1 ? that.tmpData.price.price * that
							.curPayCount :
							that.tmpData.price.money * that.curPayCount
						// 计算分红价格	
						if (that.tmpData.is_master === 1) {
							curRedMoney = that.tmpData.cur_price * that.curPayCount
						}
						// 计算积分价格
						if (that.tmpData.is_points === 1) {
							curIntMoney = that.tmpData.cur_point * that.curPayCount
						}
					}
					// console.log(curTtlMoney, curPerMoney, curOalMoney, curVipMoney, curPayMoney);
					that.curTtlMoney = curTtlMoney
					that.curPerMoney = curPerMoney
					that.curOalMoney = curOalMoney
					that.curVipMoney = curVipMoney
					that.curPayMoney = curPayMoney
					that.curRedMoney = curRedMoney
					that.curIntMoney = curIntMoney
					console.log("默认 结算金额->", that.curPayMoney);

					// 折扣
					if (that.curRate < 100 && that.curSpecs.discount !== 1) {
						that.curPayMoney = curPayMoney * that.curRate
						console.log("折扣 结算金额->", that.curPayMoney);
						resolve('success')
					}
					// 代金券
					if (Boolean(that.curCardMoney) && that.isNotTimeOut(that.curCardMoney.outtime) && (that
							.curCardMoney.factor > 0 && curPayMoney > that.curCardMoney.factor)) {
						that.curPayMoney = curPayMoney - that.curCardMoney.value
						console.log("代金券 结算金额->", that.curPayMoney);
						resolve('success')
					}

					resolve('success')
				})



			},
			/**
			 * 代金券没有过期
			 */
			isNotTimeOut(e) {
				let stamp = Date.now();
				let curTime = Date.parse(e);
				return stamp < curTime ? true : false
			},
			/**
			 * 提交订单
			 */
			async readPutOrder() {
				console.log('readPutOrder');

				if (this.tmpData.is_virtual !== 1 && !this.curAddress) {
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
					this.warn = true
					uni.showToast({
						icon: 'error',
						title: '请选择收货地址'
					})
					return
				}

				try {
					let reqsn = await this.newPostOrder()
					console.log('创建订单', reqsn);
					await this.newCalcOrder(reqsn).then(price => {
						console.log('计算价格', price);
						let payment = this.curPayMent;
						let that = this;
						uni.showModal({
							title: '提交订单',
							content: payment.text + '：' + (price / 100).toFixed(2) + ',计 ' + this
								.curPayCount +
								' 件商品, 是否要提交订单',
							success(res) {
								if (res.confirm) {
									console.log('同意');
									that.newJsapiOrder(reqsn)
								}
							}
						})
					})
				} catch (err) {
					console.error('启动失败', err);
					uni.showModal({
						title: '错误',
						content: err.resmsg
					})
					return
				}

				console.log('__test__');


			},
			/**
			 * 创建订单
			 */
			newPostOrder() {
				let host = this.sConf.host + '/weapps/newOrder/';
				let token = this.sConf.token || '';
				let data = {
					ditch: (this.tmpData.is_master === 1 && this.tmpData.is_virtual === 1) ? '代购权益' : '商品订单',
					node: this.nodeData,
					payment: this.curPayMent.value,
					products: []
				}
				let trade = {
					cid: this.tmpData.id,
					num: this.curPayCount
				}
				if (Boolean(this.curSpecs)) {
					trade.gid = this.curSpecs.id
				}
				if (this.tmpData.is_virtual !== 1) {
					data.addre = this.curAddress.id
				}
				data.products.push(trade)
				if (this.curCardGood !== null) {
					data.card_good = this.curCardGood.id
				}
				if (this.curCardMoney !== null) {
					data.card_money = this.curCardMoney.id
				}
				console.log('请求参数', data);
				return new Promise((resolve, reject) => {
					utils.authenticatorOnPost(host, token, data).then(res => {
						console.log('提交订单成功', res);
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			/**
			 * 远程计算订单金额
			 */
			newCalcOrder(e) {
				console.log('newCalcOrder', e);
				let host = this.sConf.host + '/weapps/calcOrder/';
				let token = this.sConf.token || '';
				let data = {
					reqsn: e
				}
				return new Promise((resolve, reject) => {
					utils.authenticatorOnPost(host, token, data).then(res => {
						console.log('远程计算订单金额', res);
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			/**
			 * 创建jsapi订单请求
			 */
			newJsapiOrder(e) {
				let host = this.sConf.host + '/weapps/postReqsn/';
				let token = this.sConf.token || '';
				let data = {
					reqsn: e
				}
				utils.authenticatorOnPost(host, token, data).then(res => {
					console.log('创建jsapi', res);
					utils.requestPayment(res, e)
				}).catch(err => {
					console.log('创建jsapi_失败', err);
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.goods-carts {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		position: fixed;
		left: 0;
		right: 0;
		/* #ifdef H5 */
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		bottom: 0;
	}

	.buy-price::first-letter {
		font-size: x-large;
	}

	.warn-address {
		border: 2px solid #dd524d;
		border-radius: 5px;
	}

	.toSubmitReqsn {
		background: linear-gradient(135deg, $uni-color-success, $uni-color-banner);
	}

	.disableButton {
		background-color: #888;
	}
</style>